# python/control/view_controller.py
from urllib import request

from flask import Blueprint, render_template, jsonify
from flask_login import login_required, current_user
from python.extensions import db
from python.model.car_sales import CarSales  # 导入汽车销售模型

# 创建蓝图
main_bp = Blueprint('main', __name__)
menu_bp = Blueprint('menu', __name__, url_prefix='/menu')


@main_bp.route('/')
@login_required
def index():
    """主页路由"""
    return render_template('index.html', username=current_user.username)


@menu_bp.route('/bar_example')
@login_required
def bar_example():
    """柱状图示例页面"""
    return render_template('menu/bar_example.html')




@menu_bp.route('/car_sales')
@login_required
def car_sales():
    """汽车销售数据页面"""
    return render_template('menu/car_sales.html')


@menu_bp.route('/api/car_sales')
@login_required
def api_car_sales():
    # 获取查询参数
    year = request.args.get('year', type=int)
    month = request.args.get('month', type=int)
    manufacturer = request.args.get('manufacturer')

    print("🔍 正在执行查询...")
    print(f"Year: {year}, Month: {month}, Manufacturer: {manufacturer}")

    query = CarSales.query

    if year:
        print("✅ 过滤年份:", year)
        query = query.filter(CarSales.year == year)
    if month:
        print("✅ 过滤月份:", month)
        query = query.filter(CarSales.month == month)
    if manufacturer:
        print("✅ 过滤厂商:", manufacturer)
        query = query.filter(CarSales.manufacturer.like(f'%{manufacturer}%'))

    results = query.order_by(CarSales.ranking).all()

    print("📊 查询结果数量:", len(results))

    return jsonify([{
        'year': car.year,
        'month': car.month,
        'ranking': car.ranking,
        'model': car.model,
        'manufacturer': car.manufacturer,
        'sales_volume': car.sales_volume,
        'price_range': car.price_range
    } for car in results])

@menu_bp.route('/car_sales_chart')
@login_required
def car_sales_chart():
    """汽车销售数据图表页面"""
    return render_template('menu/car_sales_chart.html')


@menu_bp.route('/api/top_sales')
@login_required
def api_top_sales():
    """获取销量前10的汽车数据"""
    results = CarSales.query.filter(
        CarSales.year == 2023,
        CarSales.month == 9
    ).order_by(
        CarSales.sales_volume.desc()
    ).limit(10).all()

    return jsonify([{
        'model': car.model,
        'sales_volume': car.sales_volume,
        'manufacturer': car.manufacturer
    } for car in results])